﻿using DreamCMS.BLL.Factory;
using DreamCMS.BLL.Factory.Interface;
using DreamCMS.Entity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DreamCMS.BLL
{
    public class CategoryManager
    {
        #region Init
        private static ICategoryDAO dao = DataAccessFactory.CreateCategoryDAO();

        private static List<CategoryInfo> catList = null;

        private static object lockHelper = new object();
        /// <summary>
        /// 构造函数，加载类别信息
        /// </summary>
        static CategoryManager()
        {
            InitCat();
        }
        /// <summary>
        /// 初始化Category缓存
        /// </summary>
        private static void InitCat()
        {
            if (catList == null)
            {
                lock (lockHelper)
                {
                    if (catList == null)
                    {
                        catList = dao.GetAllCategory();
                    }
                }
            }
        }
        /// <summary>
        /// 更新缓存
        /// </summary>
        public static void ClearCache()
        {
            CategoryManager.InitCat();
        }
        #endregion

        #region Get
        /// <summary>
        /// 根据ID获取单个分类
        /// </summary>
        /// <param name="catId">分类ID</param>
        /// <returns>分类实体</returns>
        public static CategoryInfo GetCatById(long catId)
        {
            if (CategoryManager.catList == null)
            {
                CategoryManager.InitCat();
            }
            foreach (CategoryInfo cat in catList)
            {
                if (cat.CatId == catId)
                {
                    return cat;
                }
            }
            return null;
        }
        /// <summary>
        /// 根据别名获取单个分类
        /// </summary>
        /// <param name="slug"></param>
        /// <returns></returns>
        public static CategoryInfo GetCategoryBySlug(string slug)
        {
            if (CategoryManager.catList == null)
            {
                CategoryManager.InitCat();
            }
            foreach (CategoryInfo t in catList)
            {
                if (!string.IsNullOrEmpty(slug) && t.Slug.ToLower() == slug.ToLower())
                {
                    return t;
                }
            }
            return null;
        }


        /// <summary>
        /// 获取全部分类
        /// </summary>
        /// <returns></returns>
        public static List<CategoryInfo> GetCategoryList()
        {
            if (CategoryManager.catList == null)
            {
                CategoryManager.InitCat();
            }
            return catList;
        }
        #endregion

        #region Update
        /// <summary>
        /// 更新某类别下文章数量(当添加，删除文章，修改文章类别或删除类别时要用到)
        /// </summary>
        /// <param name="catId"></param>
        /// <param name="addCount"></param>
        /// <returns>是否更新成功</returns>
        public static bool UpdateCategoryCount(long catId, long addCount)
        {
            CategoryInfo cat = GetCatById(catId);
            cat.PostCount += addCount;
            if (dao.UpdateCategory(cat) < 1) //数据库更新失败
            {
                //回滚
                cat.PostCount -= addCount;
                return false;
            }
            CategoryManager.catList.Sort();
            return false;
        }
        /// <summary>
        /// 将本类整个所有的Category信息缓存更新到数据库（同时缓存排序）
        /// </summary>
        /// <returns></returns>
        public static bool UpdateCategory()
        {
            foreach (CategoryInfo cat in catList)
            {
                if (!(dao.UpdateCategory(cat) > 0))
                {
                    return false;
                }
            }
            catList.Sort();
            return true;
        }
        /// <summary>
        /// 将某个cat信息实体更新到数据库（同时缓存排序）
        /// </summary>
        /// <param name="cat"></param>
        /// <returns></returns>
        public static bool UpdateCategory(CategoryInfo cat)
        {
            if (dao.UpdateCategory(cat) > 0)
            {
                return true;
            }
            else
            {
                //回滚
                CategoryInfo catTmp = CategoryManager.GetCatById(cat.CatId);
                cat = catTmp;
                return false;
            }

        }
        #endregion

        #region Delete
        /// <summary>
        /// 删除分类
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public static bool DeleteCategoryById(long id)
        {
            //TODO:按理说应该都有SQL语句去处理相关的关联删除问题
            if (PostManager.DeletePostsByCat(id) > 0)
            {
                if (dao.DeleteCategory(id) > 0)
                {
                    CategoryInfo cat = GetCatById(id);
                    catList.Remove(cat);
                    catList.Sort();
                    return true;
                }
            }
            return false;
        }
        #endregion

        #region Insert
        /// <summary>
        /// 插入一个分类(不需要修改分类的type因为dao里面自动处理为1类型了)
        /// </summary>
        /// <param name="cat">类别实体</param>
        /// <returns>返回新分类在数据库中的ID</returns>
        public static long InsertCategory(CategoryInfo cat)
        {
            long rel = dao.AddCategory(cat);
            if (rel > 0)
            {
                cat.CatId = rel;
                catList.Add(cat); //缓存更新
                catList.Sort();
            }
            return rel;
        }
        #endregion

        #region Others
        /// <summary>
        /// 判断类别名是否存在
        /// </summary>
        /// <param name="name">类别名</param>
        /// <returns>是否存在</returns>
        public static bool IsExistName(string name)
        {
            if (CategoryManager.catList == null)
            {
                CategoryManager.InitCat();
            }
            List<CategoryInfo> list = catList.FindAll(delegate(CategoryInfo cat) { return cat.Name == name; });
            if (list.Count > 0)
            {
                return true;
            }
            return false;
        }
        #endregion


    }
}
